package com.njupt.DoublePoint;

import threshold.ListNode;

public class RemoveNthFromEnd {


    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode p = head;
        ListNode q = head;
        int count = 0;
        while(p != null){
            count++;
            p = p.next;
        }

        int num = count -n;
        if(num == 0 && count==1){
            return null;
        }
        if(count == n){
            return head.next;
        }
        //System.out.println(num);
        while(q != null){
            num--;
            if(num == 0){
                //System.out.println(q.val);
                q.next = q.next.next;
                break;
            }
            q = q.next;
        }


        return head;
    }
    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
//        ListNode node3 = new ListNode(3);
//        ListNode node4 = new ListNode(4);
//        ListNode node5 = new ListNode(5);
        node1.next = node2;
//        node2.next = node3;
//        node3.next = node4;
//        node4.next = node5;

        RemoveNthFromEnd test = new RemoveNthFromEnd();
        ListNode listNode = test.removeNthFromEnd(node1, 2);
        ListNode p = listNode;
        while(p != null){

            System.out.print(p.val + " ");
            p = p.next;
        }

    }
}
